const FormData = require("form-data");
const axios = require("axios").default;
const rn = require("random-number");
const CommonAxerrHG = require("../tool/CommonAxerrHandler");

const get_uuid = function () {
  let arr = ['34175a19-5364-448a-a4ec-a215ee1e057d', '04d86789-0e61-4410-a990-8b67a6aa3a16', 'efcee868-1e39-47d3-8a95-3c95b6763995', 'f2e2722f-6a36-466a-9c9b-ccbc3b50139d'];
  let i = rn({ min: 0, max: arr.length - 1, integer: true });
  return arr[i];
}

/**
* @returns {Promise<{ok:Boolean,msg:String,data:{uptoken:String} }>}
*/
function getHunlijiQiniuToken() {
  return new Promise(resolve => {
    axios.get('https://www.hunliji.com/p/wedding/home/APIUtils/image_upload_token', {
      headers: {
        'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8",
        "user-agent": "okhttp/3.10.0",
        'devicekind': 'android',
        'phone': get_uuid()
      },
      validateStatus: s => s == 200
    }).then(axresp => {
      if (axresp.data && axresp.data.uptoken) {
        return resolve({
          ok: true,
          msg: "ok",
          data: {
            uptoken: axresp.data.uptoken
          }
        })
      }
      throw axresp.data;
    }).catch(axerr => {
      CommonAxerrHG(resolve)(axerr);
    })
  })
}

/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{link:String}}>}
 * @param {Buffer} str_buffer 
 */
function uploadJsonStringBuffer(str_buffer) {
  return new Promise(async resolve => {
    let o_token = await getHunlijiQiniuToken();
    if (!o_token.ok) {
      return resolve({
        ok: false,
        msg: `can not get token:${o_token.msg}`
      })
    }
    let form = new FormData;
    form.append("token", o_token.data.uptoken);
    form.append("file", str_buffer, {
      contentType: "application/json",
      filename: `${rn({ min: 1222, max: 1948 })}.json`
    });
    axios.post(`http://upload.qiniup.com`, form, {
      headers: {
        ...form.getHeaders()
      }
    }).then(axresp => {
      if (axresp.data && axresp.data.image_path) {
        return resolve({
          ok: true,
          msg: "ok",
          data: {
            link: `https://qnm.hunliji.com/${axresp.data.image_path}`
          }
        })
      }
      throw axresp.data;
      // debugger
    }).catch(axerr => {
      CommonAxerrHG(resolve)(axerr);
    })

  })
}


module.exports = {
  uploadJsonStringBuffer
}